<template>
  <view class="select-dropdown">
    <view class="select-header" @tap="toggleDropdown">
      <text class="select-text">{{ selectedLabel || placeholder }}</text>
      <text class="iconfont" :class="isOpen ? 'icon-up' : 'icon-down'"></text>
    </view>
    <view class="dropdown-list" v-if="isOpen">
      <scroll-view scroll-y class="dropdown-scroll">
        <view 
          class="dropdown-item" 
          v-for="(item, index) in options" 
          :key="index"
          @tap="selectItem(item)"
          :class="{ 'active': selectedValue === item.value }"
        >
          {{ item.label }}
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    options: {
      type: Array,
      default: () => []
    },
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  data() {
    return {
      isOpen: false,
      selectedValue: this.value,
      selectedLabel: ''
    }
  },
  watch: {
    value(newVal) {
      this.selectedValue = newVal;
      this.updateSelectedLabel();
    },
    options: {
      handler() {
        this.updateSelectedLabel();
      },
      deep: true
    }
  },
  created() {
    this.updateSelectedLabel();
  },
  methods: {
    toggleDropdown() {
      this.isOpen = !this.isOpen;
    },
    selectItem(item) {
      this.selectedValue = item.value;
      this.selectedLabel = item.label;
      this.$emit('input', item.value);
      this.$emit('change', item);
      this.isOpen = false;
    },
    updateSelectedLabel() {
      if (this.selectedValue && this.options.length > 0) {
        const selected = this.options.find(item => item.value === this.selectedValue);
        this.selectedLabel = selected ? selected.label : '';
      } else {
        this.selectedLabel = '';
      }
    },
    closeDropdown() {
      this.isOpen = false;
    }
  }
}
</script>

<style>
.select-dropdown {
  position: relative;
  width: 100%;
  z-index: 10;
}

.select-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70rpx;
  padding: 0 20rpx;
  background-color: #f5f7fa;
  border-radius: 8rpx;
  border: 1rpx solid #e4e7ed;
}

.select-text {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dropdown-list {
  position: absolute;
  top: 75rpx;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  z-index: 11;
  max-height: 300rpx;
}

.dropdown-scroll {
  max-height: 300rpx;
}

.dropdown-item {
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #f0f0f0;
}

.dropdown-item.active {
  background-color: #f0f7ff;
  color: #409EFF;
}

.dropdown-item:last-child {
  border-bottom: none;
}

.icon-down:before {
  content: "\e6e9";
}

.icon-up:before {
  content: "\e6e7";
}
</style>